package sk.naive.talker.command;

import sk.naive.talker.util.Utils;

import java.util.BitSet;

/**
 *
 * @author <a href="mailto:virgo@naive.deepblue.sk">Richard "Virgo" Richter</a>
 * @version $Revision: 1.3 $ $Date: 2004/01/29 23:13:03 $
 */
public class BitSetSelector {
	public BitSet create(String rangeSpec, int maxIndex) {
		return create(rangeSpec, "all", maxIndex);
	}

	public BitSet create(String rangeSpec, String allString, int maxIndex) {
		BitSet deleted;
		if (rangeSpec.equalsIgnoreCase(allString)) {
			deleted = new BitSet() {
				public boolean get(int bitIndex) {
					return true;
				}
			};
		} else {
			deleted = new BitSet();
			String sa[] = rangeSpec.split(",", -1);
			for (int i = 0; i < sa.length; i++) {
				String[] expr = Utils.split(sa[i], "-", 2);
				int from = Integer.parseInt(expr[0]);
				if (from > maxIndex) {
					continue;
				}
				if (expr.length == 2) {
					int to = Integer.parseInt(expr[1]);
					if (to > maxIndex) {
						to = maxIndex;
					}
					if (to < from) {
						continue;
					}
					deleted.set(from, to + 1);
				} else {
					deleted.set(from);
				}
			}
		}
		return deleted;
	}
}
